package cz.gillan.housecosts;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import cz.gillan.housecosts.data.Gauge;
import cz.gillan.housecosts.sql.GaugeDbAdapter;
import cz.gillan.housecosts.sql.StateDbAdapter;

public class GaugesActivity extends ListActivity {

	private GaugeDbAdapter gaugeDbAdapter;
	private static final int ACTIVITY_GAUGE_CREATE = 0;
	private static final int ACTIVITY_GAUGE_EDIT = 1;
	private static final int ACTIVITY_STATE_CREATE = 2;
	private static final int ACTIVITY_STATE_EDIT = 3;
	private static final int ACTIVITY_STATE_LIST = 4;
	private static final int CM_NEW_STATE = 0;
	private static final int CM_SHOW_ALL_STATES = 1;
	private static final int CM_UPDATE_GAUGE = 2;

	private List<Gauge> gauges;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gauges_list);
		ListView list  = getListView();
		list.setDividerHeight(2);
		registerForContextMenu(list);
		/*
		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				Toast.makeText(GaugesActivity.this, "You long clicked here " + position, Toast.LENGTH_LONG).show();
				return true;
			}
		});
		*/
		gaugeDbAdapter = new GaugeDbAdapter(this);
		gaugeDbAdapter.open();
		fillData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.gaugemenu, menu);
		return true;
	}

	// Reaction to the menu selection
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.gaugeMenuInsert:
			createGauge();
			return true;
		}		
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.gaugeMenuInsert:
			createGauge();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		listAllStates(gauges.get(position).getId());
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		Long gaugeId = gauges.get(info.position).getId();
		switch (item.getItemId()) {
		case CM_NEW_STATE: 
			createNewState(gaugeId);
			//fillData();
			return true;
		case CM_SHOW_ALL_STATES:
			listAllStates(gaugeId);
			return true;
		case CM_UPDATE_GAUGE:
			return true;
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
	    menu.setHeaderTitle(gauges.get(info.position).getName());
	    String[] menuItems = getResources().getStringArray(R.array.gaugesListContextMenu);
	    for (int i = 0; i < menuItems.length; i++) {
	    	menu.add(Menu.NONE, i, i, menuItems[i]);
	    }
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillData();
	}

	private void fillData() {
		Cursor cursorGauges = gaugeDbAdapter.fetchAllGauges();
		startManagingCursor(cursorGauges);
		cursorGauges.moveToFirst();
		gauges = new ArrayList<Gauge>(cursorGauges.getCount());
		while (!cursorGauges.isAfterLast()) {
			Gauge gauge = new Gauge(cursorGauges.getLong(cursorGauges.getColumnIndexOrThrow(GaugeDbAdapter.KEY_ROWID)));
			//gauge.setGaugeType()
			gauge.setMagnitude(cursorGauges.getString(cursorGauges.getColumnIndexOrThrow(GaugeDbAdapter.KEY_MAGNITUDE)));
			gauge.setName(cursorGauges.getString(cursorGauges.getColumnIndexOrThrow(GaugeDbAdapter.KEY_NAME)));
			gauge.setSerialNumber(cursorGauges.getString(cursorGauges.getColumnIndexOrThrow(GaugeDbAdapter.KEY_SERIALNUMBER)));
			gauge.setComment(cursorGauges.getString(cursorGauges.getColumnIndexOrThrow(GaugeDbAdapter.KEY_COMMENT)));
			
			Double first = 0d;
			Double last = 0d;
			Cursor cursorConsumption = gaugeDbAdapter.fetchGaugeConsumptionByCount(gauge.getId(), 2);
			startManagingCursor(cursorConsumption);
			
			if (cursorConsumption.getCount() > 0) {
				first = cursorConsumption.getDouble(cursorConsumption.getColumnIndexOrThrow(GaugeDbAdapter.KEY_FIRST_STATE));
				last = cursorConsumption.getDouble(cursorConsumption.getColumnIndexOrThrow(GaugeDbAdapter.KEY_LAST_STATE));
			}
			gauge.setFirstState(first);
			gauge.setLastState(last);
			
			gauges.add(gauge);
			cursorGauges.moveToNext();
		}
		GaugeAdapter adapter = new GaugeAdapter(this, gauges);
		setListAdapter(adapter);
	}
	
	private void createGauge() {
		Intent i = new Intent(this, GaugeEditActivity.class);
		startActivityForResult(i, ACTIVITY_GAUGE_CREATE);
	}
	
	private void createNewState(Long gaugeId) {
		Intent i = new Intent(this, StateEditActivity.class);
		i.putExtra(StateDbAdapter.KEY_GAUGEID, gaugeId);
		i.putExtra(StateDbAdapter.KEY_ROWID, -1l);
		startActivityForResult(i, ACTIVITY_STATE_EDIT);
	}
	
	private void listAllStates(Long gaugeId) {
		Intent i = new Intent(this, StatesActivity.class);
		i.putExtra(StateDbAdapter.KEY_GAUGEID, gaugeId);
		startActivityForResult(i, ACTIVITY_STATE_LIST);
	}
}
